<template>
  <div class="page-content">
    <MenuBar v-if="!isMobile" passTab="43" />

    <PhoneMenuBar v-else passTab="43" />

    <div style="height: 70px;" v-if="!isMobile"></div>

    <div class="page-product">
      <div class="product-title">最新到货</div>

      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>


      <div class="message-layout">

        <n-list bordered show-divider size="large" hoverable v-if="!isMobile">
          <n-list-item v-for="(item, index) in all_newsList" v-bind:key="index">
            <template #prefix>
              <div style="margin-left: 30px;width: 40px;
                display: flex;flex-direction: column;
                justify-content: center;align-items: center;">
                <img src="@/assets/images/png/XLS.png" style="width: 35px;margin-bottom: 5px;" />
                <div style="color: #111111;">{{ item.filesize }}KB</div>
              </div>

            </template>
            <n-thing>
              <template #header>

                <div style="display: flex;align-items: center;margin: 15px 0 15px 60px;">
                  <img src="@/assets/images/png/hot.png" v-if="index < 3"
                    style="width: 20px;height: 20px;margin-right: 5px;" />
                  <h3 style="font-size: 18px; margin: 0; font-weight: bold;">{{ item.title }}</h3>
                </div>


              </template>
              <template #description>
                <n-space size="large" style="margin:0 0 15px 60px">
                  <n-tag :bordered="false" type="info" size="large">
                    {{ item.addtime.length > 10 ? item.addtime.substring(0, 10) : item.addtime }}
                  </n-tag>
                </n-space>
              </template>

            </n-thing>
            <template #suffix>
              <n-button @click="downloadFile(item)" type="info" style="margin-right: 30px;font-size: 13px">
                立即下载
                <n-icon>
                  <img src="@/assets/images/png/下载.png" style="width: 12px;margin-left: 5px;" />
                </n-icon></n-button>
            </template>
          </n-list-item>
        </n-list>

        <n-list bordered show-divider size="large" hoverable v-else>

          <n-list-item v-for="(item, index) in all_newsList" v-bind:key="index">
            <div style="display: flex;align-items: center;">

              <div style="width: 40px;
                display: flex;flex-direction: column;
                justify-content: center;align-items: center;">
                <img src="@/assets/images/png/XLS.png" style="width: 35px;margin-bottom: 5px;" />
                <div style="color: #111111;">{{ item.filesize }}KB</div>
              </div>


              <div style=" margin-left: 15px;width: 100%;">
                <div style="font-size: 16px; font-weight: bold;margin-bottom: 5px;">{{ item.title }}</div>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                  <n-tag :bordered="false" type="info" size="small">
                    {{ item.addtime.length > 10 ? item.addtime.substring(0, 10) : item.addtime }}
                  </n-tag>
                  <n-icon size="30" color="#0075c1" @click="downloadFile(item)">
                    <ArrowDownCircleOutline />
                  </n-icon>
                </div>

              </div>



            </div>


          </n-list-item>

        </n-list>

      </div>


      <div style="display: flex;justify-content: center;margin-top: 15px;" v-if="!isMobile">
        <n-pagination class="pagination" v-model:page="pageNum" :page-count="totalNum" :page-sizes="[pageSize]"
          size="large" @update:page="handlePageChange1" :theme-overrides="paginationThemeOverrides" show-quick-jumper />
      </div>

      <div v-else style="display: flex;justify-content: space-between;align-items: center;margin-top: 15px;">

        <n-button type="info" @click="pageNumOnClick('-')" :style="{ visibility: pageNum != 1 ? 'visible' : 'hidden' }">
          上一页
        </n-button>

        <div style="width: 80px;"><n-select v-model:value="pageNum" @update:value="handlePageNumValue"
            :options="pageNumOptions" filterable /></div>

        <n-button type="info" @click="pageNumOnClick('+')" :style="{ visibility: pageNum != totalNum ? 'visible' : 'hidden' }">
          下一页
        </n-button>
      </div>

    </div>

    <BottomBar />
  </div>
</template>

<script setup name="productListPage">
import { ArrowDownCircleOutline } from '@vicons/ionicons5'

import { API_URL } from '@/config'
import { newarrivals } from '@/api'
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import MenuBar from '@/components/MenuBar.vue'
import PhoneMenuBar from '@/components/PhoneMenuBar.vue'
import BottomBar from '@/components/BottomBar.vue'
// 创建一个响应式变量来存储是否为移动设备
const isMobile = ref(false);

// 定义一个函数来检查用户代理
const checkDevice = () => {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;

  // 设置isMobile的值
  isMobile.value = /android/i.test(userAgent) || /iPhone|iPad|iPod/i.test(userAgent);
};

const sortList = [{ id: -1, name: '从新到旧' }, { id: 999, name: '从旧到新' }]


const typeId = ref(-1)


const all_newsList = ref([])
const totalNum = ref(0)
const pageSize = 10
const getNewsList = async () => {
  const params = {
    page: pageNum.value,
    size: pageSize,
    navbar_id: 43
  }
  const result = await newarrivals(params)

  console.log("newsList", result)

  if (result != null && result.data != null) {

    // if (typeId.value == -1) {
    //   all_newsList.value = result.data
    // } else {
    //   all_newsList.value = result.data.reverse()
    // }

    all_newsList.value = result.data.map(item => {
      return {
        ...item,
        downloadurl: item.downloadurl?.startsWith('../') ? API_URL + item.downloadurl.substring(2) : item.downloadurl
      }
    })

    const totalCount = result.total;

    const fullPages = Math.floor(totalCount / pageSize); // 完整页数
    const remainder = totalCount % pageSize;             // 余数

    totalNum.value = remainder > 0 ? fullPages + 1 : fullPages;

    pageNumOptions.value = []
    for (let i = 1; i <= totalNum.value; i++) {
      pageNumOptions.value.push({ label: i + "", value: i + "" })
    }
  }
}

const downloadFile = (item) => {
  console.log("aaaa", item.downloadurl)

  // 假设这是你的文件URL
  const fileUrl = item.downloadurl;
  const fileName = item.title + '.xls'; // 指定下载的文件名

  console.log("fileName", fileName)
  // // 创建一个隐藏的可下载链接
  const link = document.createElement('a');
  link.href = fileUrl;
  link.download = fileName; // 设置下载的文件名
  link.style.display = 'none';

  // 将链接添加到DOM中
  document.body.appendChild(link);
  // 触发点击
  link.click();
  // 移除链接
  document.body.removeChild(link);
}


const route = useRoute()

onMounted(async () => {
  checkDevice();

  const categoryId = route.query.typeId || -1
  typeId.value = categoryId

  getNewsList()
});
const pageNum = ref(1)
const chooseCategory = async (categoryId) => {
  // console.log("chooseCategory", categoryId)
  typeId.value = categoryId;
  pageNum.value = 1;
  getNewsList()
}

const handlePageChange = (page) => {
  console.log('当前页:', page)
  getNewsList()
}

const handlePageChange1 = (page) => {
  console.log('当前页:', page)
  getNewsList()

  window.scrollTo({
    top: 0,
    behavior: 'smooth'  // 平滑滚动
  });
}

watch(
  () => route.query.typeId,
  (newId) => {
    typeId.value = newId || -1
    console.log("typeId.value", typeId.value)
    if (typeId.value != -1)
      getNewsList()
  },
  { immediate: true }
)

// 自定义分页主题样式
const paginationThemeOverrides = {

  // 👇 这些是官方支持的 overrides 属性
  itemColor: '#ffffff',                    // 默认背景
  itemColorHover: '#f0f0f0',               // 悬停背景
  itemColorActive: '#00aeff',              // 选中背景（蓝色）
  itemColorActiveHover: '#00aeff',         // 选中悬停
  textColor: '#333333',                    // 默认文字
  textColorActive: '#ffffff',              // ✅ 选中文字颜色（白色）
  itemBorder: '1px solid #d9d9d9',         // 边框
  itemBorderHover: '1px solid #00aeff',    // 悬停边框
  itemBorderActive: '1px solid #00aeff',   // 选中边框

}

function pageNumOnClick(type) {

  if (type == "+") {
    pageNum.value++;
  } else {
    pageNum.value--;
  }

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}
const pageNumOptions = ref([])

function handlePageNumValue(e) {
  console.log("handlePageNumValue", pageNum.value)

  getNewsList()

  window.scrollTo({
    top: 0,
    // behavior: 'smooth'  // 平滑滚动
  });
}
</script>

<style scoped lang="scss">
/* 容器样式 */
.page-content {
  width: 100vw;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;


  @media (min-width: 769px) {
    .page-product {
      padding: 15px 120px;
      flex: 1;

      .product-title {
        color: #111111;
        font-size: 30px;
        font-weight: bold;
        line-height: 140%;
        margin-bottom: 15px;
      }

      .page-filter {
        display: flex;
        align-items: center;
        margin-top: 15px;
        background-color: white;
        padding: 10px 20px;
        height: 52px;


        .condition {
          color: #111111;
          font-size: 14px;
          margin-right: 50px;
          line-height: 130%;
          font-weight: bold;
        }

        .product-list {
          display: flex;
          gap: 10px;
          flex: 1;


          .product-item {
            font-size: 12px;
            font-weight: 700;
            padding: 4px;
            width: 100px;
            height: 36px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            background-color: #5a5757;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */
            cursor: pointer;
          }


          .product-item:hover {
            background-color: #787575;
          }
        }
      }


      .message-layout {
        margin-top: 15px;
        background: white;
        padding: 50px;

      }

    }
  }


  /* 手机端样式 */
  @media (max-width: 768px) {
    .page-product {
      margin-top: 70px;
      padding: 15px;


      .product-title {
        color: #111111;
        font-size: 18px;
        font-weight: bold;
        // margin-bottom: 15px;
      }

      .page-filter {
        display: flex;
        align-items: center;
        margin-top: 15px;
        background-color: white;
        padding: 15px;



        .condition {
          color: #111111;
          font-size: 14px;
          margin-right: 8px;
          width: 60px;
          font-weight: 500;
        }


      }



      .message-layout {
        margin-top: 15px;
        background: white;
        padding: 5px;

        .message-content {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          /* 可省略，-webkit-line-clamp 会处理 */
          word-break: break-word;
          max-width: 100%;
          min-height: 40px;
        }
      }

    }
  }

  :deep(.n-pagination) {
    /* 强制重置所有 Pagination 相关变量 */
    --n-item-text-color-active: #ffffff !important;
    /* ✅ 关键：白色 */
    --n-item-text-color-hover: #333333 !important;
  }

}
</style>